package com.example.wnn.develop.other;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FileUtils;

public class ReadLoaclFile {


    public static void main(String[] args) throws IOException {
        File file = new File("/Users/wenzheng/Desktop/shop/repiar.txt") ;
        String content = FileUtils.readFileToString(file,"UTF-8");
        JSONArray jsonArray = JSON.parseArray(content);
        List<Map<String,Object>> items =  ( List)jsonArray;
        for (Map<String, Object> item : items) {
            Integer id = MapUtil.getInt(item,"id");
            String avatar = MapUtil.getStr(item,"avatar");
            try {
                if (StrUtil.isNotBlank(avatar)){
                    download(avatar,id);
                }
            }catch (Exception r){
                System.out.println("下载异常："+id);
                r.printStackTrace();
            }
        }
    }




    //java 通过url下载图片保存到本地

    public static void download(String urlString, int i) throws Exception {

        // 构造URL

        URL url = new URL(urlString);

        // 打开连接

        URLConnection con = url.openConnection();

        // 输入流

        InputStream is = con.getInputStream();

        // 1K的数据缓冲

        byte[] bs = new byte[1024];

        // 读取到的数据长度

        int len;

        // 输出的文件流

        String filename = "/Users/wenzheng/Desktop/task/unPhone/" + i + ".jpg";  //下载路径及下载图片名称

        File file = new File(filename);

        FileOutputStream os = new FileOutputStream(file, true);

        // 开始读取

        while ((len = is.read(bs)) != -1) {

            os.write(bs, 0, len);

        }

       // System.out.println(i);

        // 完毕，关闭所有链接

        os.close();

        is.close();

    }



}
